package com.party.admin.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.party.common.constant.WechatConstant;
import com.party.common.utils.DateUtils;
import com.party.common.utils.StringUtils;
import com.party.common.utils.wechat.WechatUtils;
import com.party.core.model.collect.SystemModuleCollect;
import com.party.core.model.system.TargetType;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.collect.ISystemModuleCollectService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Description: 小程序访问同步微信数据到服务器
 * @Author: yangshoukun
 * @Date: 2018/6/22 15:28
 */
@Component(value = "quartzXcxVisit")
public class QuartzXcxVisit {
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private ISystemModuleCollectService systemModuleCollectService;

    // 是否需要刷新小程序token
    @Value("#{wechat['wechat.xcx.refreshToken']}")
    private String refreshToken;

    /**
     * 相册小程序appid
     */
    @Value("#{wechat['wechat.xcx_photo.appid']}")
    private String photoXcxAppId;

    /**
     * 打卡小程序appid
     */
    @Value("#{wechat['wechat.xcx_sign.appid']}")
    private String signXcxAppId;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 同步相册小程序昨天的数据到服务器
     */
    public void updatePhotoYesterday() {
        if (refreshToken.equals(Boolean.TRUE.toString())) {
            Date date = DateUtils.yesterday();

            SystemModuleCollect module = systemModuleCollectService.findByModuleAndDate(TargetType.PHOTO.getCode(), date);
            if (null == module) {
                String yesterday = DateUtils.formatDate(date, "yyyyMMdd");
                WechatOpenMember wechatOpenMember = wechatOpenMemberService.findByAppid(photoXcxAppId);
                String url = WechatConstant.XCX_VISIT_ANALYZE.replace("ACCESS_TOKEN", wechatOpenMember.getAuthorizerAccessToken());

                Map<String, String> param = Maps.newHashMap();
                param.put("begin_date", yesterday);
                param.put("end_date", yesterday);

                JSONObject jsonObject = WechatUtils.httpRequest(url, WechatUtils.POST, JSONObject.toJSONString(param));
                String errcode = null == jsonObject.get("errcode") ? "" : jsonObject.get("errcode").toString();
                if (StringUtils.isNotEmpty(errcode)) {
                    logger.error("同步相册小程序昨天的数据到服务器异常：{}，APPID：{}，AccessToken：{}，params:{}",
                            jsonObject.toJSONString(), photoXcxAppId, wechatOpenMember.getAuthorizerAccessToken(), JSONObject.toJSONString(param));
                } else {
                    JSONArray list = (JSONArray) jsonObject.get("list");
                    JSONObject object = (JSONObject) list.get(0);
                    Long pv = Long.valueOf(object.get("visit_pv").toString());
                    Long uv = Long.valueOf(object.get("visit_uv").toString());

                    SystemModuleCollect moduleCollect = new SystemModuleCollect(TargetType.PHOTO.getCode(), date, pv, uv);
                    systemModuleCollectService.insert(moduleCollect);
                }
            }
        }
    }

    /**
     * 同步打卡小程序昨天的数据到服务器
     */
    public void updateSignYesterday() {
        if ("true".equals(Boolean.TRUE.toString())) {
            Date date = DateUtils.yesterday();

            SystemModuleCollect module = systemModuleCollectService.findByModuleAndDate(TargetType.SIGN.getCode(), date);
            if (null == module) {
                String yesterday = DateUtils.formatDate(date, "yyyyMMdd");
                WechatOpenMember wechatOpenMember = wechatOpenMemberService.findByAppid(signXcxAppId);
                String url = WechatConstant.XCX_VISIT_ANALYZE.replace("ACCESS_TOKEN", wechatOpenMember.getAuthorizerAccessToken());

                Map<String, String> param = Maps.newHashMap();
                param.put("begin_date", yesterday);
                param.put("end_date", yesterday);

                JSONObject jsonObject = WechatUtils.httpRequest(url, WechatUtils.POST, JSONObject.toJSONString(param));
                String errcode = null == jsonObject.get("errcode") ? "" : jsonObject.get("errcode").toString();
                if (StringUtils.isNotEmpty(errcode)) {
                    logger.error("同步打卡小程序昨天的数据到服务器异常：{}，APPID：{}，AccessToken：{}，params:{}",
                            jsonObject.toJSONString(), signXcxAppId, wechatOpenMember.getAuthorizerAccessToken(), JSONObject.toJSONString(param));
                } else {
                    JSONArray list = (JSONArray) jsonObject.get("list");
                    JSONObject object = (JSONObject) list.get(0);
                    Long pv = Long.valueOf(object.get("visit_pv").toString());
                    Long uv = Long.valueOf(object.get("visit_uv").toString());

                    SystemModuleCollect moduleCollect = new SystemModuleCollect(TargetType.SIGN.getCode(), date, pv, uv);
                    systemModuleCollectService.insert(moduleCollect);
                }
            }
        }
    }
}
